<template>
  <el-dialog :title="dialogTit"
             :close-on-click-modal="false"
             :visible.sync="dialogVisible"
             width="860px">
    <!-- 新增编辑 -->
    <el-form ref="form"
             class="add-edit-box"
             :model="form"
             label-width="136px"
             :disabled="opType==='view' || opType==='audit' || opType==='back'">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="年份"
                        prop="year"
                        :rules="[required]">
            <el-date-picker v-model="form.year"
                            type="year"
                            placeholder="请选择"
                            value-format="yyyy"
                            style="width:100%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="adCd"
                        label="行政区划"
                        :rules="[required]">
            <el-select filterable
                       class="w100p"
                       v-model="form.adCd"
                       @change="adCdChange">
              <el-option v-for="item in districtOptions"
                         :key="item.adCd"
                         :label="item.adNm"
                         :value="item.adCd">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="cooMecFile"
                        label="协调机制文件名称"
                        :rules="[required]">
            <el-input v-model.trim="form.cooMecFile"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="cooMecTypes"
                        label="协调机制类型">
            <el-select clearable
                       filterable
                       multiple
                       v-model="form.cooMecTypes"
                       class="w100p">
              <el-option v-for="item in cooMecTypeOptions"
                         :key="item.dictValue"
                         :label="item.dictLabel"
                         :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="fileNum"
                        label="文号">
            <el-input v-model.trim="form.fileNum"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="printTime"
                        label="建立时间"
                        :rules="[required]">
            <el-date-picker v-model="form.printTime"
                            style="width:100%"
                            type="month"
                            placeholder="请选择建立时间"
                            value-format="yyyy-MM"
                            :clearable="false"
                            :editable="false">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="memberUnits"
                        label="成员单位"
                        :rules="[required]">
            <el-tooltip placement="top"
                        effect="light"
                        :disabled="form.memberUnits.length<2">
              <div slot="content">{{memberUnitsMultipleText}}</div>
              <el-select clearable
                         filterable
                         multiple
                         collapse-tags
                         v-model="form.memberUnits"
                         class="w100p"
                         :rules="[required]">
                <el-option v-for="item in companyOptions"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue">
                </el-option>
              </el-select>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider>协调机制负责人召集人</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="dutyName"
                        label="姓名"
                        :rules="[required]">
            <el-input v-model.trim="form.dutyName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="dutyUnit"
                        label="所在单位"
                        :rules="[required]">
            <el-select clearable
                       filterable
                       v-model="form.dutyUnit"
                       class="w100p"
                       :rules="[required]">
              <el-option v-for="item in dutyUnitOptions"
                         :key="item.dictValue"
                         :label="item.dictLabel"
                         :value="item.dictValue">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="dutyJob"
                        label="党政职务"
                        :rules="[required]">
            <el-input v-model.trim="form.dutyJob"></el-input>
            <!-- <el-select clearable
                       filterable
                       v-model="form.dutyJob"
                       class="w100p">
              <el-option v-for="item in dutyJobOptions"
                         :key="item.dictValue"
                         :label="item.dictLabel"
                         :value="item.dictValue">
              </el-option>
            </el-select> -->
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item prop="downPath"
                        label="附件上传"
                        class="tips-form-item">
            <button @click.prevent="openFile"
                    class="upload-file-btn">附件</button>
            <!-- 提示 -->
            <el-popover class="tips-pop"
                        placement="top-start"
                        title="提示"
                        width="240"
                        trigger="hover"
                        content="上传协调机制文件等佐证材料。">
              <i class="el-icon-question tips-icon"
                 slot="reference"></i>
            </el-popover>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="remark"
                        label="备注">
            <el-input placeholder=""
                      type="textarea"
                      :rows="3"
                      resize="none"
                      :maxlength="500"
                      v-model.trim="form.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 审核 -->
    <Water-save-single-audit ref="WaterSaveSingleAudit"
                             :opType="opType"
                             v-show="opType==='audit' || (opType==='view' && form.status ==='2') || (opType==='view' && form.status ==='3')"
                             @singleAuditSubmit="singleAuditSubmie"></Water-save-single-audit>

    <!-- 退回 -->
    <Water-save-single-back ref="WaterSaveSingleBack"
                            :opType="opType"
                            v-show="opType==='back' || (opType==='edit' && form.status ==='4')"
                            @singleBackSubmit="singleBackSubmit"></Water-save-single-back>

    <!-- 按钮 -->
    <div class="op-btn-box">
      <el-button @click="dialogVisible = false">关 闭</el-button>
      <el-button type="primary"
                 @click="submit"
                 v-show="['add','edit'].includes(opType)">确 定</el-button>
      <el-button type="success"
                 @click="handleAudit"
                 v-show="opType==='audit'">审 核</el-button>
      <el-button type="warning"
                 @click="handleBack"
                 v-show="opType==='back'">退 回</el-button>
    </div>

    <!-- 附件上传 -->
    <upload-file ref="uploadFileDialog"
                 :configName="'用水效率管理文件上传'"
                 :fileList="form.downPath"
                 :uploadDisabled="opType==='view' || opType==='audit' || opType==='back'"
                 @saveFile="saveFile"></upload-file>
  </el-dialog>
</template>

<script>
import {
  addCoordinationMechanismSetUp, editCoordinationMechanismSetUp, auditCoordinationMechanismSetUp, belongCompanyOptions,
  governmentPostsOptions
} from '@/api/businessManagement/waterUseEfficiencyControl/waterSaveManagement/coordinationMechanism/coordinationMechanismSetUpTable';
import { commonCompanyOptions } from '@/api/businessManagement/waterUseEfficiencyControl/waterSaveManagement/waterSavePublicityEducation/waterSaveEducationTable';
import WaterSaveSingleAudit from '@/views/businessManagement/waterUseEfficiencyControl/components/single-audit';
import WaterSaveSingleBack from '@/views/businessManagement/waterUseEfficiencyControl/components/single-back';
import { districtOptionsMixin } from '@/mixins/districtOptionsMixin.js';
import uploadFile from '@/views/components/uploadFile/index'
import dayjs from "dayjs";
export default {
  name: 'AddEditMechanismSetUp',
  mixins: [districtOptionsMixin],
  components: {
    WaterSaveSingleAudit,
    uploadFile,
    WaterSaveSingleBack
  },
  props: {
    cooMecTypeOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      opType: 'add', // 操作类型:add：新增  edit:编辑  view:查看  audit:审核
      form: {
        year:'',
        adCd: '', // 行政区划
        cooMecFile: '', // 协调机制文件名称
        fileNum: '', // 文号
        cooMecTypes: [], // 协调机制类型
        printTime: '', // 建立时间
        memberUnits: [], // 成员单位
        dutyName: '', // 姓名
        dutyUnit: '', // 所在单位
        dutyJob: '', // 党政职务
        downPath: '', // 附件
        remark: '', // 备注
      },
      required: {
        required: true,
        message: '必填，不能为空',
        trigger: ['blur', 'change']
      },
      currentRow: null,
      companyOptions: [],
      dutyUnitOptions: [], // 所在单位选项
      dutyJobOptions: [] // 党政职务选项
    }
  },
  computed: {
    // 弹窗名称
    dialogTit() {
      let opTypeText = this.opType === 'add' ? '新增' : this.opType === 'edit' ? '编辑' : this.opType === 'view' ? '查看' : this.opType === 'audit' ? '审核' : '退回';
      return `${opTypeText}协调机制建立台账信息`
    },
    // 成员单位多选项选中值显示
    memberUnitsMultipleText() {
      let text = '';
      let { memberUnits } = this.form;
      if (memberUnits.length !== 0) {
        memberUnits.forEach(item => {
          let findCompany = this.companyOptions.find(o => o.dictValue === item);
          // console.log(findCompany)
          if (findCompany) {
            text += findCompany.dictLabel + '; '
          }
        })
      }
      return text
    }
  },
  methods: {
    open(currentRow = null, opType = 'add') {
      this.currentRow = currentRow;
      this.opType = opType;
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.$refs.WaterSaveSingleAudit.resetForm(currentRow);
        this.$refs.WaterSaveSingleBack.resetForm(currentRow);
        if (this.opType !== 'add') {
          this.assignmentForm(currentRow)
        } else {
          this.form.year = `${new Date().getUTCFullYear()}`;
          this.form.printTime = dayjs().format('YYYY-MM');
          this.form.adCd = this.districtOptions[0].adCd; // 新增赋值行政区划
          this.getCompanyOptions(this.form.adCd)
          this.getBelongCompanyOptions(this.form.adCd);
          this.getGovernmentPostsOptions(this.form.adCd);
        }
      })
    },
    // 行政区划选项改变
    adCdChange(adCd) {
      this.form.memberUnits = [];
      this.form.dutyUnit = '';
      this.form.dutyJob = '';
      this.getCompanyOptions(adCd);
      this.getBelongCompanyOptions(adCd);
      this.getGovernmentPostsOptions(adCd);
    },
    // 获取单位选项
    async getCompanyOptions(adCd) {
      let { status, data } = await commonCompanyOptions(adCd)
      if (status == 200) {
        this.companyOptions = data;
      }
    },
    // 获取所在单位选项
    async getBelongCompanyOptions(adCd) {
      let { status, data } = await belongCompanyOptions(adCd)
      if (status == 200) {
        this.dutyUnitOptions = data;
      }
    },
    // 获取党政职务选项
    async getGovernmentPostsOptions(adCd) {
      let { status, data } = await governmentPostsOptions(adCd)
      if (status == 200) {
        this.dutyJobOptions = data;
      }
    },
    // 表单赋值
    assignmentForm(rowData) {
      this.form = { ...this.form, ...rowData }
      this.form.cooMecTypes = [...rowData.cooMecTypes]
      this.form.memberUnits = [...rowData.memberUnits]
      this.getCompanyOptions(rowData.adCd)
      this.getBelongCompanyOptions(rowData.adCd);
      this.getGovernmentPostsOptions(rowData.adCd);
    },
    // 打开附件上传弹窗
    openFile() {
      this.$refs.uploadFileDialog.open()
    },
    // 获取上传的文件
    saveFile(fileList) {
      let url = fileList.join('|');
      this.form.downPath = url
    },
    // 提交保存
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.opType === 'add') {
            this.handleAdd()
          } else if (this.opType === 'edit') {
            this.handleEdit()
          }
        } else {
          this.msgWarning('请正确填写表单内容')
        }
      });
    },
    // 添加
    async handleAdd() {
      let { status, errors } = await addCoordinationMechanismSetUp(this.form)
      if (status == 200) {
        this.msgSuccess('操作成功');
        this.$parent.search();
        this.dialogVisible = false;
      } else {
        this.msgError(`错误${status}：${errors[0].message}`)
      }
    },
    // 编辑
    async handleEdit() {
      let { status, errors } = await editCoordinationMechanismSetUp(this.form)
      if (status == 200) {
        this.msgSuccess('操作成功');
        this.$parent.search();
        this.dialogVisible = false;
      } else {
        this.msgError(`错误${status}：${errors[0].message}`)
      }
    },
    // 审核操作
    handleAudit() {
      this.$refs.WaterSaveSingleAudit.handleAudit()
    },
    // 审核提交
    async singleAuditSubmie(auditData) {
      let params = { ...auditData }
      params.idList = this.form.id;
      let { status, errors } = await auditCoordinationMechanismSetUp(params)
      if (status == 200) {
        this.msgSuccess('操作成功');
        this.$parent.search();
        this.dialogVisible = false;
      } else {
        this.msgError(`错误${status}：${errors[0].message}`)
      }
    },
    // 退回操作
    handleBack() {
      this.$refs.WaterSaveSingleBack.handleBack()
    },
    // 退回提交
    singleBackSubmit(backData) {
      // console.log(backData)
      this.singleAuditSubmie(backData)
    }
  },
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/water-save-form.scss";
</style>